package com.light.gulimall.seckill.interceptor;

import com.light.common.vo.MemberRespVO;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    public static ThreadLocal<MemberRespVO> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        HttpSession session = request.getSession();
        MemberRespVO loginUser = (MemberRespVO) session.getAttribute("loginUser");

        String requestURI = request.getRequestURI();
        //拦截秒杀请求
        boolean match = new AntPathMatcher().match("/kill", requestURI);
        if (match) {
            if (loginUser == null) {
                session.setAttribute("msg","请先进行登录");
                response.sendRedirect("http://auth.gulimall.com/login.html");
                return false;
            } else {
                threadLocal.set(loginUser);
                return true;
            }
        }

        return true;
    }
}
